//
//  OAuthViewController.swift
//  WeiboSwift
//
//  Created by Apple13 on 16/7/10.
//  Copyright © 2016年 yupeng. All rights reserved.
//
//App key：3950284697
//App secret：b4c8f797496fc929c31bf86897f3fe8d

import UIKit

import SVProgressHUD
import AFNetworking


//定义全局常量
let WeiboAppkey = "3950284697"
let WeiboAppSecret = "b4c8f797496fc929c31bf86897f3fe8d"
//微博授权回调页
let WeiboRedirect_Uri = "http://www.baidu.com"



class OAuthViewController: UIViewController {
    
    
    //MARK: - 懒加载控件
    private lazy var webView:UIWebView = UIWebView()
    
//MARK: - 初始化函数
    override func loadView() {
        webView.delegate = self
//       webView.opaque = false //把默认的不透明改成透明
        view = webView
        webView.backgroundColor  = UIColor.greenColor()
        setUpNaviUI()
        requestOAuthLogin()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.redColor()
        
    }
    
    //1⃣️申请授权
    private func requestOAuthLogin(){
        
        //请求地址   http://open.weibo.com/wiki/Oauth2/authorize
        let  url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppkey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        
        let nsurl = NSURL(string: url)
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        //加载
        webView.loadRequest(request)
        
    }

    // 设置导航栏样式
    private func setUpNaviUI() {
        
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消",target: self,action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title:"快速填满",target: self,action: "autoFillAction")
        
        
    }


    
    //MARK: - 导航栏点击事件
    //✒️✒️ 为按钮绑定的点击事件函数名前要加 @objc
    @objc  private func cancelAction() {
        SVProgressHUD.dismiss()
        print("点击了取消")
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
       
    }
    
    
    
   @objc private func autoFillAction() {
        print("点击了填满")
     webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18627708188'; document.getElementById('passwd').value = 'weibo19901218'")
    }
    
    //2⃣️通过授权码(code)获取accessToken----📕需要用封装的方法进行网络调用
    //✒️✒️ 每次的授权码不一样么
    
    private func requestAccesstoken11(code:String){
        
        NetWorkTools.shareTools.requestAccesstoken(code) { (response, error) in
            if error != nil{
                
                print(error)
                return
            }
            
            //执行到这里,回调成功
            guard let dict = response as? [String:AnyObject] else{
                print("不是json")
                return
            }
            
            //是正常的字典
            let userAccount = UserAccount(dict:dict)
            print(userAccount)
            print("👗👗👗")
            //调用获取用户信息的函数
            self.requsetUserInfo11(userAccount)
            
        }
        
        
        
        
        
    }
    
    //3⃣️获取用户信息
    private func requsetUserInfo11(userAccount:UserAccount){
        
        NetWorkTools.shareTools.requestUserInfo(userAccount) { (response, error) in
            
            if error != nil{
                print(error)
                return
            }
            
            guard let dict = response as? [String:AnyObject] else {
                print("不是正经的json格式")
                return
            }
            
            //执行到这里一定有着
            let name = dict["name"]
            let avatar_large = dict["avatar_large"]
            
            //设置用户名和头像
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //保存用户对象
            //✒️✒️此处获得的用户信息不完整
            userAccount.saveUserAccount()
            print("1⃣️")
            print(userAccount)
            print("1⃣️")
            
        }
        
    }
    
    
}




extension OAuthViewController:UIWebViewDelegate {
    //1⃣️.5 通过重定向获得授权码
    ////同意授权后会重定向
//    http://www.example.com/response&code=CODE
    //‼️此处的代码是自动执行????????
    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    print("➡️在此处设置重定向")
        
        guard let url = request.URL else {
            return false
        }
        
        //  代码执行到此,我们的url一定有值
        //  获取url的绝对地址
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        //  代码执行到此就是我们需要关心的url字符串
        
        if let query = url.query where query.hasPrefix("code=") {
            //  截取code
            let code = query.substringFromIndex("code=".endIndex)
            
            print("‼️code: " + code)
         
            //requestAccesstoken(code)
//✒️✒️_____________________________________________________________
            
            UserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSuccess) in
                if isSuccess {
                    print("🐸登录成功")
                    self.dismissViewControllerAnimated(false, completion: { 
                        print("这里要发送通知✅")
                        //✒️✒️通知步骤1⃣️--postNotificationName(<#T##aName: String##String#>, object: <#T##AnyObject?#>, userInfo: <#T##[NSObject : AnyObject]?#>)
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self, userInfo: nil)
                        
                    })
                }else{
                    print("登录失败")
                }
            })
            
            
            
            
            
            
//✒️✒️_____________________________________________________________
        }else{//进入取消回调页
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        
        
        return true
    }
    
    
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    
    
    
}
